/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.psc.controllers;

import com.mycompany.psc.ejb.UsersManager;
import com.mycompany.psc.entities.Users;
import com.mycompany.psc.producers.LoggedIn;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author A7med
 */
@Named
@SessionScoped
public class Login implements Serializable {

    @EJB
    private UsersManager usersManager;
    private Users current;

    public String logout() {
        System.out.println("loging out");

        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        HttpSession session = (HttpSession) ec.getSession(true);

        session.invalidate();
        try {
            ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
        } catch (IOException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;

    }

    public String login() {
        Users logged = usersManager.validateUser();

        if (logged != null) {
            current = logged;
            System.out.println("logged=" + logged.getName());
            return "/index?faces-redirect=true";

        } else {
            FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Login", ""));
            return null;
        }
    }

    public boolean isLoggedIn() {

        return current != null;

    }

    @Produces
    @LoggedIn
    public Users getCurrent() {
        return current;
    }

}
